$(function ()
{
	$('#actionSelector').empty();
	
	jQuery.each(
		Action.types, function (actionName)
		{
			$('#actionSelector').append(
				'<span id="action' + actionName + '" class="clickable">'
				+ actionName
				+ '</span>');
			
			$('#action' + actionName).click(function ()
				{
					var action = Action.types[actionName];

					if (action.type === Action.SIMPLE) {
						if (action.fields.length === 0) {
							// This simple action has no subfields, execute it now

							(new Action(actionName)).execute();
						} else {
							// Simple action, iterate over fields and add them to the page

							$('#actionFields').empty();

							jQuery.each(
								action.fields, function ()
								{
									var fieldHTML = '<div><label>' + this.name + ': ',
										addAutoCompleter = false;

									switch (this.type) {
										case Action.Atoms.STREAM:
											// Select menu of stream names

											fieldHTML += Stream.select(this.name + 'Field');

											break;

										case Action.Atoms.TIMESTAMP:
											// TODO : Limit values, aid input for timestamps

											fieldHTML += '<input id="' + this.name + 'Field" type="time">';

											break;

										case Action.Atoms.VALUE:
											// Input for float value

											fieldHTML += '<input id="' + this.name + 'Field" type="number">';

											addAutoCompleter = true;

											break;

										case Action.Atoms.SQL:
										case Action.Atoms.BINARY:
										case Action.Atoms.TERNARY:
										case Action.Atoms.ITERATOR:
											// Input for complex value

											fieldHTML += '<input id="' + this.name + 'Field" type="text">';

											addAutoCompleter = true;

											break;
									}

									fieldHTML += '</label></div>';

									$('#actionFields').append(fieldHTML);

									if (addAutoCompleter) {
										AutoCompleter.list[this.type].attach('#' + this.name + 'Field');
									}
								});

							// TODO : Clicking this button must create and execute the Action
							$('#actionFields').append('<div><button id="executeAction">Execute action</button></div>');

							$('#executeAction').click(function ()
							{
								var actionObj = new Action(actionName),
									data = {};
								
								jQuery.each(
									action.fields, function ()
									{
										data[this.name] = $('#' + this.name + 'Field').val();
									});
								
								actionObj.build(data);
								
								actionObj.execute();
							});
						}
					}

					event.stopPropagation();
				});
		});
});
